<template>
  <div class="wang-editor-container">
    <Toolbar class="wang-editor-toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor class="wang-editor-content" style=" overflow-y: auto;" :style="'height:'+height" v-model="valueHtml"
      :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="handleChange" />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'

import { onBeforeUnmount, ref, shallowRef, watch, computed } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// import { calcFileSign } from "@/utils/crypto";

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  mode: {
    type: String,
    default: 'default',
    validator: (value) => ['default', 'simple'].includes(value)
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  height: {
    type: [String, Number],
    default: '500px'
  }
})

const emit = defineEmits(['update:modelValue', 'change', 'created','destroyed'])

const editorRef = shallowRef()
const valueHtml = ref(props.modelValue)
const isDestroying = ref(false)
// const ossClient = inject('ossClient');

const editorHeight = computed(() => {
  if (typeof props.height === 'number') {
    return `${props.height}px`
  }
  return props.height
})

const toolbarConfig = {
}
console.log('VITE_APP_BASE_API', import.meta.env.VITE_APP_BASE_API)
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/common/config" // 上传的图片服务器地址
console.log('VITE_APP_BASE_API', uploadUrl)
const editorConfig = {
  maxLength:5000,
  placeholder: props.placeholder,
  scroll: false,
  // MENU_CONF: {
  //   uploadImage: {
  //     customUpload: async (file, insertFn) => {
  //       // 覆盖默认的上传行为，可以自定义上传文件的请求，然后把返回的资源路径赋值给表单的 url
  //       // 文件签名
  //       const fileSign = await calcFileSign(file);
  //       // 文件名称
  //       const fileName = `${fileSign}.${file.name.split('.').pop()}`
  //       // 1.请求上传接口
  //       ossClient.value.put(`images/${fileName}`, file).then(res => {
  //         let url = ossClient.value.domain + "/images/" + fileName;
  //         insertFn(url)
  //       }).catch(err => {
  //         proxy.$modal.msgError("上传失败");
  //       })

  //     },
  //   },
  //   uploadVideo: {
  //     async customUpload(file, insertFn) {
  
  //       // 文件签名
  //       const fileSign = await calcFileSign(file);
  //       // 文件名称
  //       const fileName = `${fileSign}.${file.name.split('.').pop()}`
  //       // 1.请求上传接口
  //       ossClient.value.put(`videos/${fileName}`, file).then(res => {
  //         let url = ossClient.value.domain + "/videos/" + fileName;

  //         insertFn(url)
  //       }).catch(err => {
  //         proxy.$modal.msgError("上传失败");
  //       })
  //     },
  //   }
  // }
}

onBeforeUnmount(() => {
  console.log('组件销毁了')
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {

  editorRef.value = editor
  emit('created', editor)
}

// 自定义错误处理
const handleEditorError = (error) => {
  if (error.message.includes('Cannot resolve a Slate node')) {
    console.warn('Slate节点解析错误，尝试恢复...')
    try {
      if (editorRef.value) {
        const html = editorRef.value.getHtml()
        editorRef.value.setHtml(html)
        editorRef.value.restoreSelection()
      }
    } catch (e) {
      console.error('恢复失败:', e)
    }
  }
}

// 安全销毁方法
const destroyEditor = async () => {
  // console.error('destroyEditor:')
  // if (!editorRef.value || isDestroying.value) return
  
  // isDestroying.value = true
  // try {
  //   // 1. 移除所有事件监听
  //   editorRef.value.off('error', handleEditorError)
    
  //   // 2. 清空内容
  //   editorRef.value.setHtml('')
    
  //   // 3. 执行销毁
  //   await new Promise(resolve => {
  //     editorRef.value.destroy()
  //     resolve()
  //   })
    
  //   // 4. 触发销毁事件
  //   emit('destroyed')
  // } catch (error) {
  //   console.error('编辑器销毁异常:', error)
  // } finally {
  //   editorRef.value = null
  //   isDestroying.value = false
  // }
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
}

const handleChange = (editor) => {
  const html = editor.getHtml()
  valueHtml.value = html
  emit('update:modelValue', html)
  emit('change', html)
}

watch(() => props.modelValue, (newVal) => {
  if (newVal !== valueHtml.value) {
    valueHtml.value = newVal
    if (editorRef.value) {
      editorRef.value.setHtml(newVal)
    }
  }
})
// 暴露方法给父组件
defineExpose({
  destroyEditor,
})
</script>

<style scoped>
.wang-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.wang-editor-toolbar {
  border-bottom: 1px solid #dcdfe6;
}

.wang-editor-content {
  overflow-y: auto;
}
</style>